package Arrays;

/**
 * 作者:hfj
 * 功能:169.多数元素
 * 日期: 2025/10/27 17:42
 */
public class MajorityElement {

    public static void main(String[] args) {
        int[] nums = {2,2,1,1,1,2,2};
        System.out.println(majorityElement(nums));
    }

    //找到数组中存在最多的元素
    public static int majorityElement(int[] nums) {
        int count = 1,max = nums[0];

        for (int i = 1; i < nums.length; i++) {
            if (max == nums[i]){
                count++;
            }else {
                count--;
                if (count == 0){
                    max = nums[i+1];
                }
            }
        }
        return max;
    }
}
